package com.example.demo.config.base;

import com.example.demo.config.tool.CamelCase;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 所有实体服务层的父接口，实现了一些自定义接口;
 * @param <T>
 * @param <S>
 */

@NoRepositoryBean
public interface DataService<T, S> extends JpaRepository<T, S> {
    default Page<T> findAll(Example<T> example, Integer page, Integer size, String sortDirection, String sortColumn){
        Pageable pageable;
        if(sortDirection == null || sortColumn == null){
            pageable = PageRequest.of(page, size);
        }else {
            List<Sort.Order> list = new ArrayList<>();
            list.add(new Sort.Order(Sort.Direction.fromString(sortDirection), CamelCase.toCamelCase(sortColumn)));
            Sort sort = Sort.by(list);
            pageable = PageRequest.of(page, size, sort);
        }

        if(example == null){
            return this.findAll(pageable);
        }else {
            return this.findAll(example, pageable);
        }

    }

    default Page<T> findAll(Integer page, Integer size, String sortDirection, String sortColumn){
        return this.findAll(null, page, size, sortDirection, sortColumn);
    }

    default Page<T> findAll(Integer page, Integer size){
        return this.findAll(null, page, size, null, null);
    }

    default Page<T> findAll(Example<T> example, Integer page, Integer size){
        return this.findAll(example, page, size, null, null);
    }

    Page<T> findAll(Integer page, Integer size, String sortDirection);
    Page<T> findAll(Example<T> example, Integer page, Integer size, String sortDirection);
}
